import { TableColumnProps } from "ant-design-vue";
import {
  AcitivityDefItem,
  AcitivityDefStatus,
  ActivityCarrier,
  ActivityCondition,
  ActivityConditionType,
  ActivityType,
  ObtainWays,
  UseActivityHookResult,
} from "/@/api/main/marketing/models";
import { h, ref } from "vue";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  ModelRules,
} from "/@/components/CURDDialog/models";
import { enumToOptions, getLabelByValueFromEnum } from "/@/utils/common";
import ActivityCarrierFormItem from "./ActivityCarrierFormItem.vue";
import ObtainLimitFormItem from "./ObtainLimitFormItem.vue";
import CustomRangeFormItem from "./CustomRangeFormItem.vue";
import { getActivityScheduleList } from "/@/api/main/marketing";
import dayjs from "dayjs";
import ActivityConditionFormItem from "./ActivityConditionFormItem.vue";
import EditorFormItem from "/@/components/EditorFormItem.vue";

export default function (): UseActivityHookResult {
  let addText = "新增活动详情",
    pageTitle = "活动详情定义",
    editText = "编辑活动详情",
    deleteText = "确认删除该活动详情吗？",
    innerColumns: TableColumnProps<Partial<AcitivityDefItem>>[] = [
      {
        title: "活动档期",
        dataIndex: "activityScheduleName",
      },
      {
        title: "活动详情名称",
        dataIndex: "activityDetailName",
      },
      {
        title: "活动类型",
        dataIndex: "activityType",
        customRender({ text }) {
          return getLabelByValueFromEnum(text, ActivityType, "activityType");
        },
      },
      {
        title: "活动条件",
        dataIndex: "activityCondition",
        customRender({ text, record }) {
          if (text === ActivityCondition.all) return "不限";
          if (text === ActivityCondition.orderPrice) {
            return `订单金额 ${getLabelByValueFromEnum(
              record.conditionType as ActivityConditionType,
              ActivityConditionType,
              "activityConditionType"
            )} ${record.conditionValue}`;
          }
          return "--";
        },
      },
      {
        title: "活动载体",
        dataIndex: "activityCarrier",
        customRender({ text }) {
          return getLabelByValueFromEnum(text, ActivityCarrier, "activityCarrier");
        },
      },
      {
        title: "投放数量",
        dataIndex: "putNum",
      },
      {
        title: "用户限定数量",
        dataIndex: "obtainLimitNum",
        customRender({ text, record }) {
          if (record.isObtainLimit) {
            return text;
          }
          return "不限数量";
        },
      },
      {
        title: "日期期限",
        dataIndex: "startPeriod",
        customRender({ record }) {
          if (record.isPermanently) {
            return "长期";
          }
          return dayjs(record.startPeriod).format("YYYY-MM-DD") + "~" + dayjs(record.endPeriod).format("YYYY-MM-DD");
        },
      },
      {
        title: "时段",
        dataIndex: "startTime",
        customRender({ record }) {
          if (record.isAllDay) {
            return "全天";
          }
          return record.startTime + "~" + record.endTime;
        },
      },
      {
        title: "状态",
        dataIndex: "status",
      },
      {
        title: "操作",
        key: "oper",
        fixed: "right",
        width: 100,
      },
      // {
      //   title: "出库单类型",
      //   dataIndex: "deliveryType",
      //   customRender({ text }) {
      //     return getLabelByValueFromEnum(text, DeliveryType, "deliveryType");
      //   },
      // },
      // {
      //   title: "活动起始日期",
      //   dataIndex: "deliveryDate",
      //   customRender({ text }) {
      //     return dayjs(text).format("YYYY-MM-DD");
      //   },
      // },
    ];
  const model = ref<Partial<AcitivityDefItem>>({
    activityScheduleId: null,
    activityDetailName: "",
    activityType: ActivityType.tuan,
    activityUrl: "",
    _activityCondition: {
      activityCondition: ActivityCondition.all,
      conditionType: ActivityConditionType.gte,
      conditionValue: null,
    },
    _activityCarrier: null,
    putNum: null,
    _obtainLimitNum: null,
    _periodRange: { range: [], isAll: false },
    _timeRange: { range: [], isAll: false },
    activitySort: 1,
    description: "",
  });
  const scheduleList = ref<AcitivityDefItem[]>([]);
  const modelFormSetting = ref<FormItemData<Partial<AcitivityDefItem>>[]>([
    {
      key: "activityScheduleId",
      label: "活动档期",
      type: FormItemComponentType.SELECT,
      async getData() {
        const data = await getActivityScheduleList();
        scheduleList.value = data || [];
        return data ? data.map((el) => ({ value: el.id, label: `${el.activityName}(${el.activityTheme})` })) : [];
      },
      required: true,
    },
    {
      key: "activityDetailName",
    },
    {
      key: "activityType",
      label: "活动类型",
      type: FormItemComponentType.SELECT,
      props: {
        options: enumToOptions(ActivityType, "activityType"),
      },
      required: true,
    },
    {
      key: "activityUrl",
      label: "活动图片",
      type: FormItemComponentType.IMGUPLOAD,
    },
    {
      key: "_activityCondition",
      label: "活动条件",
      customComponent: h(ActivityConditionFormItem),
      required: true,
      holdRow: true,
    },
    {
      key: "_activityCarrier",
      label: "活动载体",
      customComponent: h(ActivityCarrierFormItem),
      required: true,
      holdRow: true,
    },
    {
      key: "putNum",
      type: FormItemComponentType.NUMBER,
      label: "投放数量",
      props: {
        min: 1,
      },
      required: true,
      holdRow: true,
    },
    {
      key: "_obtainLimitNum",
      label: "用户限定数量",
      customComponent: h(ObtainLimitFormItem),
      required: true,
      holdRow: true,
    },
    {
      key: "_periodRange",
      customComponent: h(CustomRangeFormItem),
      label: "有效期",
      required: true,
      holdRow: true,
      props: {
        isTime: false,
      },
    },
    {
      key: "_timeRange",
      customComponent: h(CustomRangeFormItem),
      label: "时段",
      required: true,
      holdRow: true,
      props: {
        isTime: true,
      },
    },
    {
      key: "activitySort",
      label: "活动排序",
      type: FormItemComponentType.NUMBER,
      holdRow: true,
    },
    {
      key: "description",
      label: "活动内容",
      customComponent: h(EditorFormItem),
      holdRow: true,
      props: {
        height: 250,
      },
    },
  ]);
  // const modelRules: ModelRules = [
  //   {
  //     _activityCarrier: [
  //       {
  //         required: true,
  //         message: "请设置活动载体",
  //       },
  //       {
  //         validator(rule, value) {
  //           const activityCarrier = model.value._activityCarrier?.activityCarrier;
  //           const activityType = model.value.activityType;
  //           if(activityType === ActivityType.tuan) {
  //             if(activityCarrier !== ActivityCarrier.product) {
  //               return Promise.reject("团购只能选择商品作为载体");
  //             }
  //           }
  //           if (value !== model.value.password) {
  //             return Promise.reject("两次输入的密码不一致");
  //           }
  //           return Promise.resolve();
  //         },
  //       },
  //     ],
  //   },
  // ];
  function beforeUpdateModel(record: AcitivityDefItem) {
    if (record.isPermanently) {
      record._periodRange = { range: ["", ""], isAll: true };
    } else if (record.startPeriod && record.endPeriod) {
      record._periodRange = {
        range: [dayjs(record.startPeriod).format("YYYY-MM-DD"), dayjs(record.endPeriod).format("YYYY-MM-DD")],
        isAll: false,
      };
    }
    if (record.isAllDay) {
      record._timeRange = { range: ["", ""], isAll: true };
    } else if (record.startTime && record.endTime) {
      record._timeRange = {
        range: [record.startTime, record.endTime],
        isAll: false,
      };
    }
    record._activityCondition = {
      activityCondition: record.activityCondition,
      conditionType: record.conditionType,
      conditionValue: record.conditionValue,
    };
    record._activityCarrier = {
      activityCarrier: record.activityCarrier,
      obtainWays: record.obtainWays,
      couponsId: record.couponsId,
      goodsId: record.goodsId,
      couponsName: record.coupons?.couponsName,
      goodsName: record.goods?.name,
      consumeValue: record.consumeValue,
    };
    record._obtainLimitNum = {
      isObtainLimit: record.isObtainLimit,
      obtainLimitNum: record.obtainLimitNum,
    };
  }
  function innerBeforeOk({ model, action }: CURDModalEvent<Partial<AcitivityDefItem>>) {
    if (model) {
      if (model._periodRange) {
        model.startPeriod = dayjs(model._periodRange.range[0]).valueOf();
        model.endPeriod = dayjs(model._periodRange.range[1]).valueOf();
        model.isPermanently = model._periodRange.isAll;
        delete model._periodRange;
      }
      if (model._timeRange) {
        model.startTime = model._timeRange.range[0];
        model.endTime = model._timeRange.range[1];
        model.isAllDay = model._timeRange.isAll;
        delete model._timeRange;
      }
      if (model._activityCarrier) {
        model.activityCarrier = model._activityCarrier.activityCarrier;
        model.obtainWays = model._activityCarrier.obtainWays;
        if (model.activityCarrier === ActivityCarrier.coupon) {
          model.couponsId = model._activityCarrier.couponsId;
        } else {
          model.goodsId = model._activityCarrier.goodsId;
        }
        model.consumeValue = model._activityCarrier.consumeValue;
        delete model._activityCarrier;
      }
      if (model._obtainLimitNum) {
        model.isObtainLimit = model._obtainLimitNum.isObtainLimit;
        model.obtainLimitNum = model._obtainLimitNum.obtainLimitNum;
        delete model._obtainLimitNum;
      }
      if (model._activityCondition) {
        model.activityCondition = model._activityCondition.activityCondition;
        model.conditionType = model._activityCondition.conditionType;
        model.conditionValue = model._activityCondition.conditionValue;
        delete model._activityCondition;
      }
      if (action === CURDAction.CREATE) {
        model.status = AcitivityDefStatus.waiting;
      }
      if (model.activityScheduleId) {
        const target = scheduleList.value.find((el) => el.id === model.activityScheduleId);
        if (target) {
          model.activityScheduleName = target.activityName;
        }
      }
    }
  }
  return {
    addText,
    pageTitle,
    editText,
    deleteText,
    innerColumns,
    model,
    modelFormSetting,
    innerBeforeOk,
    beforeUpdateModel,
    // modelRules,
  };
}
